/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sd.rmi.auction.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author blackdevil
 */
public class MultiClientProcess {

    private final static int MAXCLIENT = 20;

    public static void main(String arg[]) {
        try {
            int numClient = (new Random().nextInt(MAXCLIENT));
            System.out.println("Client number " + numClient);
            Process[] p = new Process[numClient];
            ProcessBuilder[] pb = new ProcessBuilder[numClient];
            BufferedReader[] stdInput = new BufferedReader[numClient];
            BufferedReader[] stdError = new BufferedReader[numClient];
            for (int i = 0; i < numClient; i++) {
                System.out.println("init Process" + i);
                File dir1 = new File(".");
                File dir2 = new File("build/classes/");
                pb[i] = new ProcessBuilder("java","sd.rmi.auction.client.Client","-cp " );
                pb[i].directory(dir2);
                p[i] = pb[i].start();                
                stdInput[i] = new BufferedReader(new InputStreamReader(p[i].getInputStream()));
                stdError[i] = new BufferedReader(new InputStreamReader(p[i].getErrorStream()));
            }// read the output from the command
            for(int i = 0 ; i < numClient; i++)
            {
                p[i].waitFor();
                System.out.println("Exit status of process : " + i + " is : " + p[i].exitValue());
            }
            
            String s = null;
            for (int i = 0; i < numClient; i++) {
                System.out.println("Stdout of process : "+  i);
                while ((s = stdInput[i].readLine()) != null) {
                    System.out.println(s);
                }
                // read any errors from the attempted command
                
                while ((s = stdError[i].readLine()) != null) {
                    System.out.println("Stderr of process : "+  i);
                    System.out.println(s);
                }
                Thread.sleep(1000);                
            }

        } catch (InterruptedException ex) {
            Logger.getLogger(MultiClientProcess.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(MultiClientProcess.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }
}
